<?php

namespace Wap\Controller;
use Think\Image;
use User\Model\LiveModel;
use Wap\Service\WeixinService;
use User\Model\FactoryModel;

class LiveController extends WapController
{
    public $wxuser;
    public function __construct()
    {
        parent::__construct();
        $this->_handleCriteriaWxuser();
    }

    private function _handleCriteriaWxuser()
    {
        $live_id = I("live_id", -1, "");
        $topic_id = I("topic_id", -1, "");
        if($live_id != -1){
            $where_room["id"] = $live_id;
            $token = M( "live_room" )->where($where_room)->getField("reserve");
            $this->wxuser = WeixinService::getWxuser($token);
            if ($_SERVER['HTTP_HOST'] == '192.168.1.137') {         //本地和测试服务器
                $openid = get_client_ip();
                session('live_openid_'.$live_id, $openid);
            }
        }
        if($topic_id != -1){
            $where_topic["id"] = $topic_id;
            $live_topic = M('live_topic')->where($where_topic)->find();
            $this->wxuser = WeixinService::getWxuser($live_topic["token"]);
            if ($_SERVER['HTTP_HOST'] == '192.168.1.137') {         //本地和测试服务器
                $openid = get_client_ip();
                session('live_openid_'.$live_topic['room_id'], $openid);
            }
        }
    }

    public function index()
    {
        $code = I('get.code', '', '');
        $live_id = I('get.live_id', -1, '');
        $openid = session('live_openid_'.$live_id);
        $wxConfig = array();
        if($this->_is_weixin()){
            if($code){
                $wechat = new \Wap\Service\WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
                $out = $wechat->snsapiUserInfo($this->wxuser['appid'], $this->wxuser['appsecret'], $code);
                if($out != null){
                    session('live_openid_'.$live_id, $out['openid']);
                    session('live_avatar_'.$live_id, $out['headimgurl']);
                    session('live_nickname_'.$live_id, $out['nickname']);
                }
                $wx = WeixinService::getWxuser($this->wxuser['token']);
                $wxJSApi = WeixinService::buildWXJSApi($wx);
                if(!empty($wxJSApi)) {
                    $wxConfig = array(
                        'appId' => $wx['appid'],
                        'nonceStr' => $wxJSApi['noncestr'],
                        'timestamp' => $wxJSApi['timestamp'],
                        'signature' => $wxJSApi['sha1']
                    );
                }
                $this->assign("wxConfig", $wxConfig);
                $this->display();
            }else{
                if($openid){
                    $wx = WeixinService::getWxuser($this->wxuser['token']);
                    $wxJSApi = WeixinService::buildWXJSApi($wx);
                    if(!empty($wxJSApi)) {
                        $wxConfig = array(
                            'appId' => $wx['appid'],
                            'nonceStr' => $wxJSApi['noncestr'],
                            'timestamp' => $wxJSApi['timestamp'],
                            'signature' => $wxJSApi['sha1']
                        );
                    }
                    $this->assign("wxConfig", $wxConfig);
                    $this->display();
                }else{
                    $wechat = new \Wap\Service\WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
                    $forward = 'http://'.$_SERVER['HTTP_HOST'].'/Wap/Live/index?'.$_SERVER['QUERY_STRING'];
                    $url = $wechat->snsapiUserInfoLink($forward, $this->wxuser['appid']);
                    redirect($url);
                }
            }
        }else{
            if(!$openid){
                $openid = $this->_getRandCode();
                session('live_openid_'.$live_id, $openid);
                session('live_avatar_'.$live_id, "");
                session('live_nickname_'.$live_id, "游客_".$openid);
            }
            $wx = WeixinService::getWxuser($this->wxuser['token']);
            $wxJSApi = WeixinService::buildWXJSApi($wx);
            if(!empty($wxJSApi)) {
                $wxConfig = array(
                    'appId' => $wx['appid'],
                    'nonceStr' => $wxJSApi['noncestr'],
                    'timestamp' => $wxJSApi['timestamp'],
                    'signature' => $wxJSApi['sha1']
                );
            }
            $this->assign("wxConfig", $wxConfig);
            $this->display();
        }
    }

    private function _is_weixin() {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

    private function _getRandCode()
    {
        $charts = "abcdefghjkmnpqrstuvwxyz0123456789";
        $max = strlen($charts);
        $noncestr = "";
        for($i = 0; $i < 7; $i++)
        {
            $noncestr .= $charts[mt_rand(0, $max)];
        }
        return $noncestr;
    }
    //=============================================wap接口开始=========================================================
    /*
     * 接口返回status：1正常返回，
     *                -1参数缺少，
     *                -2参数不合法，
     *                -3openid缺少，
     *                -4微信签名失败，
     *                -5数据库异常，
     *                -6密码不正确，
     *                -7还未登录，
     *                -8图片上传失败
     */

    //1. 用户方
    public function liveDetail()
    {
        $live_id = I('get.live_id', -1);
        if($live_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'live_id missing'));
        }
        $where_room["id"] = $live_id;
        $where_room["status"] = LiveModel::ROOM_ACTIVE;
        $live_room = M('live_room')->where($where_room)->find();
        if(!empty($live_room)){
            //info
            $background = $live_room['poster'] ? C('SITE_URL') . $live_room['poster'] : '';
            $where_user["id"] = $live_room['userid'];
            $live_user = M('live_user')->where($where_user)->find();
            $avatar = $live_user['avatar'] ? C('SITE_URL') .$live_user['avatar'] : '';
            //topicList
            $condition['room_id'] = $live_id;
            $condition['status'] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
            $live_topic = M("live_topic")->where($condition)->order("createdate desc")->select();
            $list = array();
            $time = time();
            if(!empty($live_topic)){
                foreach ($live_topic as $value){
                    if($value['topic_type'] == LiveModel::TOPIC_TYPE_VIDEO){
                        $poster = $value['video_poster'];
                    }elseif($value['topic_type'] == LiveModel::TOPIC_TYPE_MSG){
                        $poster = $value['msg_poster'];
                    }else{
                        $poster = $value['video_poster'];
                    }
                    //回放icon
                    $reserve = json_decode($value['reserve'], true);
                    //话题状态, 0 已结束 1正在直播 2即将开始 6回放
                    $startdate = strtotime($value['startdate']);
                    $enddate = strtotime($value['enddate']);
                    if($value['topic_type'] == LiveModel::TOPIC_TYPE_MSG){
                        if($enddate < $time){
                            $status = 0;
                            $order = 3;
                        }elseif($startdate > $time){
                            $status = 2;
                            $order = 2;
                        }else{
                            $status = 1;
                            $order = 1;
                        }
                    }elseif($value['topic_type'] == LiveModel::TOPIC_TYPE_VIDEO){//视频直播按照APP端开启直播表示正在直播
                        if($reserve['replay'] == LiveModel::REPLAY_TRUE){
                            $status = 6;        //出现回放icon
                            $order = 3;
                        }else{
                            if($value['status'] == LiveModel::TOPIC_PAUSE){
                                $status = 1;
                                $order = 1;
                            }else{
                                $where_stat["reserve"] = $value['id'];
                                $live_stat = M('live_stat')->where($where_stat)->order('id desc')->find();
                                if(!empty($live_stat)){
                                    if($live_stat['enddate'] == ''){
                                        $status = 1;
                                        $order = 1;
                                    }else{
                                        $status = -1;   //不显示该话题
                                        $order = 3;
                                    }
                                }else{
                                    $status = 2;
                                    $order = 2;
                                }
                            }
                        }
                    }else{
                        if($reserve['replay'] == LiveModel::REPLAY_TRUE){
                            $status = 3;        //出现回放icon
                            $order = 3;
                        }else{
                            if($value['status'] == LiveModel::TOPIC_PAUSE){
                                $status = 1;
                                $order = 1;
                            }else{
                                $where_stat["reserve"] = $value['id'];
                                $live_stat = M('live_stat')->where($where_stat)->order('id desc')->find();
                                if(!empty($live_stat)){
                                    if($live_stat['enddate'] == ''){
                                        $status = 1;
                                        $order = 1;
                                    }else{
                                        $status = 0;        //已结束
                                        $order = 3;
                                    }
                                }else{
                                    $status = 2;
                                    $order = 2;
                                }
                            }
                        }
                    }
                    if($status != -1){
                        $flag[]=$order;
                        $list[] = array(
                            'topic_id' => $value['id'],
                            'liveType' => $value['topic_type'],
                            'title' => $value['topic_title'],
                            'info' => $value['topic_title'],
                            'image' => $poster?C('SITE_URL').$poster:'',
                            'status' => $status,
                            'date' => date('Y-m-d', strtotime($value['startdate'])),
                            'order' => $order
                        );
                    }
                }
                //array_multisort($flag, SORT_ASC, $list);
            }
            //qrcode
            $qrImage = $this->wxuser['headerpic']?C('SITE_URL').$this->wxuser['headerpic']:C('SITE_URL').
                '/Public/images/home/zbgyEcode.jpg';
            $qrTxt = '长按二维码关注后,您可获得更多资讯';
            $forceQrTxt = '长按二维码,关注后方可继续收看';

            $this->ajaxReturn(array('status' => 1,
                'title' => $live_room['title'], 'background' => $background, 'avatar' => $avatar,
                'introduce' => $live_room['info'],
                'list' => $list,
                'qrImage' => $qrImage, 'qrTxt' => $qrTxt, 'forceQrTxt' => $forceQrTxt
            ));
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid live_id'));
        }
    }

    public function topicDetail()
    {
        $topic_id = I('get.topic_id', -1);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        $this->_statistics($topic_id, 'page_view');
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M('live_topic')->where($where_topic)->find();
        if(!empty($live_topic)){
            //info
            $title = $live_topic['topic_title'];
            $where_user["roomid"] = $live_topic['room_id'];
            $where_user["status"] = LiveModel::USER_ACTIVE;
            $avatar = M('live_user')->where($where_user)->getField('avatar');
            $logo = $avatar?C('SITE_URL').$avatar:'';
            $where_room["id"] = $live_topic['room_id'];
            $where_room["status"] = LiveModel::ROOM_ACTIVE;
            $name = M('live_room')->where($where_room)->getField('title');
            $reserve = json_decode($live_topic['reserve'],true);
            if($live_topic['topic_type'] == LiveModel::TOPIC_TYPE_VIDEO){
                $banner = '';
                $poster = $live_topic['video_poster']?C('SITE_URL').$live_topic['video_poster']:'';
            }elseif($live_topic['topic_type'] == LiveModel::TOPIC_TYPE_MSG){
                $banner = $reserve['banner']?C('SITE_URL').$reserve['banner']:'';
                $poster = '';
            }else{
                $banner = $reserve['banner']?C('SITE_URL').$reserve['banner']:'';
                $poster = $live_topic['video_poster']?C('SITE_URL').$live_topic['video_poster']:'';
            }
            //直播状态，0 已结束 1正在直播 2即将开始
            $startdate = strtotime($live_topic['startdate']);
            $enddate = strtotime($live_topic['enddate']);
            if($live_topic['topic_type'] == LiveModel::TOPIC_TYPE_MSG){
                if($enddate < time()){
                    $topic_status = 0;
                }elseif($startdate > time()){
                    $topic_status = 2;
                }else{
                    $topic_status = 1;
                }
                $topic_type = $live_topic['topic_type'];
            }elseif($live_topic['topic_type'] == LiveModel::TOPIC_TYPE_VIDEO){      //视频直播的状态以APP端开播时间为准
                if($reserve['replay'] == LiveModel::REPLAY_TRUE){
                    $topic_status = 6;      //视频回放
                }else{
                    if($live_topic['status'] == LiveModel::TOPIC_PAUSE){
                        $topic_status = 4;
                    }else{
                        $where_stat["reserve"] = $topic_id;
                        $live_stat = M('live_stat')->where($where_stat)->order('id desc')->find();
                        if(!empty($live_stat)){
                            if($live_stat['enddate'] == ''){
                                $topic_status = 1;
                            }else{
                                $topic_status = 0;
                            }
                        }else{
                            $topic_status = 2;
                        }
                    }
                }
                $topic_type = $live_topic['topic_type'];
            }else{
                if($reserve['replay'] == LiveModel::REPLAY_TRUE){
                    $topic_status = 6;
                    $topic_type = $live_topic['topic_type'];
                }else{
                    if($live_topic['status'] == LiveModel::TOPIC_PAUSE){
                        $topic_status = 4;
                    }else{
                        $where_stat["reserve"] = $topic_id;
                        $live_stat = M('live_stat')->where($where_stat)->order('id desc')->find();
//                        if(!empty($live_stat)){
//                            if($live_stat['enddate'] == ''){
//                                $topic_status = 1;
//                                $topic_type = $live_topic['topic_type'];
//                            }else{
//                                $topic_status = 0;
//                                $topic_type = LiveModel::TOPIC_TYPE_MSG;        //取消切换到视频的按钮
//                            }
//                        }else{
//                            $topic_status = 2;
//                            $topic_type = $live_topic['topic_type'];
//                        }
                        $topic_status = 1;
                        $topic_type = $live_topic['topic_type'];
                    }
                }
            }
            //liveStream
            $pc_address = $address = '';
            $live_time = 0;
            $replay = 0;
            if($live_topic['topic_type'] != LiveModel::TOPIC_TYPE_MSG){
                if($reserve['replay'] == LiveModel::REPLAY_TRUE){
                    $replay = 1;
                    $where_stat["reserve"] = $topic_id;
                    $live_stat = M('live_stat')->where($where_stat)->order('id desc')->find();
                    $pc_address = $address = $reserve['replay_address'];
                    $stat_start_time = strtotime($live_stat['startdate']);
                    $stat_end_time = strtotime($live_stat['enddate']);
                    $live_time = $stat_end_time - $stat_start_time;
                }else{
                    if(!empty($live_topic["output_stream"])){
                        $address = $live_topic["output_stream"];
                        $pc_address = $live_topic["input_stream"];
                    }else{
                        $address = 'http://139.219.196.0:7936/live'.$topic_id.'.m3u8';
                        $pc_address = 'http://139.219.196.0/hls/live'.$topic_id;
                    }
                    //按照APP端直播时间
                    $where_stat["reserve"] = $topic_id;
                    $live_stat = M('live_stat')->where($where_stat)->order('id desc')->find();
                    if(!empty($live_stat)){
                        $stat_start_time = strtotime($live_stat['startdate']);
                        $stat_end_time = strtotime($live_stat['enddate']);
                        if($stat_end_time != '' && $stat_end_time > 0){
                            $live_time = $stat_end_time - $stat_start_time;
                        }else{
                            $live_time = time() - $stat_start_time;
                        }
                    }else{
                        $live_time = 0;
                    }
                }
            }
            //support
            $support = json_decode($live_topic['support'], true);
            $support_comment_all = ($support['support_comment']==LiveModel::SUPPORT_ACTIVE)?1:0;
            $support_comment = ($support['support_comment']==LiveModel::SUPPORT_ACTIVE)?1:0;
            $support_follow = ($support['support_follow']==LiveModel::SUPPORT_ACTIVE)?1:0;
            $follow_delay_time = $support['follow_delay_time'];
            $support_online_num = ($support['support_online_num']==LiveModel::SUPPORT_ACTIVE)?1:0;
            $online_multi = $support['online_multi'];
            $support_praise = ($support['support_praise']==LiveModel::SUPPORT_ACTIVE)?1:0;
            $support_comment_check = ($support['support_comment_check']==LiveModel::SUPPORT_ACTIVE)?1:0;
            $openid = session('live_openid_'.$live_topic['room_id']);
            if(!empty($openid)){
                $where_member["topic_id"] = $topic_id;
                $where_member["openid"] = $openid;
                $where_member["status"] = LiveModel::MEMBER_SILENT;
                $silent_member = M('live_member')->where($where_member)->find();
                if(!empty($silent_member)){
                    $support_comment = 0;
                }
            }else{
                $support_comment = 0;
            }
            //praise_num
            $where_statistics["topic_id"] = $topic_id;
            $where_statistics["status"] = LiveModel::STAT_ACTIVE;
            $praise_num = M('live_statistics')->where($where_statistics)->sum('praise_num');
            $cache = S('live_topic_'.$topic_id);
            $praise_num = $praise_num + $cache['praise_num'];
            //ad
            $ad_link = $live_topic['ad_link'];
            $ad_image = $live_topic['ad_image']?C('SITE_URL').$live_topic['ad_image']:'';
            //rec_replay
            $rec_replay_all = array();
            $rec_replay = $reserve['rec_replay']?$reserve['rec_replay']:LiveModel::REPLAY_FALSE;
            if($rec_replay == LiveModel::REPLAY_TRUE){
                $rec_replay_id = explode(',', $reserve['rec_replay_id']);
                if(!empty($rec_replay_id)){
                    foreach ($rec_replay_id as $rec){
                        if($rec != 0){
                            $where_topic_rec["id"] = $rec;
                            $live_topic_rec = M('live_topic')->where($where_topic_rec)->find();
                            $rec_replay_all[] = array(
                                'image' => $live_topic_rec['video_poster'] ?
                                    C('SITE_URL').$live_topic_rec['video_poster'] : '',
                                'topic_id' => $rec
                            );
                        }
                    }
                }
            }

            $this->ajaxReturn(array('status' => 1,
                'title' => $title, 'logo' => $logo, 'name' => $name, 'banner' => $banner, 'poster' => $poster,
                'liveType' => $topic_type, 'topic_status' => $topic_status,
                'date' => date('Y-m-d', strtotime($live_topic['startdate'])), 'pc_address' => $pc_address,
                'address' => $address, 'live_time' => $live_time, 'support_comment_all' => $support_comment_all,
                'support_comment' => $support_comment, 'support_follow' => $support_follow,
                'follow_delay_time' => $follow_delay_time, 'support_online_num' => $support_online_num,
                'support_praise' => $support_praise, 'support_comment_check' => $support_comment_check,
                'praise_num' => $praise_num,
                'ad_link' => $ad_link, 'ad_image' => $ad_image,
                'replay' => $replay,
                'rec_replay' => $rec_replay, 'rec_replay_all' => $rec_replay_all
            ));
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function userInfo()
    {
        $live_id = I("get.live_id", -1);
        if($live_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'live_id missing'));
        }
        $where_room["id"] = $live_id;
        $where_room["status"] = LiveModel::ROOM_ACTIVE;
        $live_room = M("live_room")->where($where_room)->find();
        if(!empty($live_room)){
            $openid = session('live_openid_'.$live_id);
            $nickname = session('live_nickname_'.$live_id);
            if(!empty($openid)){
                //userinfo
                $nickname = $nickname?$nickname:'';
                //followstatus
                if($this->_followStatus($live_id)){
                    $this->ajaxReturn(array('status' => 1, 'nickname' => $nickname, 'follow' => 1));
                }else{
                    $this->ajaxReturn(array('status' => 1, 'nickname' => $nickname, 'follow' => 0));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid live_id'));
        }
    }

    public function memberAuth()
    {
        $topic_id = I("get.topic_id", -1);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $openid = session('live_openid_' . $live_topic['room_id']);
            $nickname = session('live_nickname_' . $live_topic['room_id']);
            if(!empty($openid)){
                $where_member["topic_id"] = $topic_id;
                $where_member["openid"] = $openid;
                $member = M('live_member')->where($where_member)->find();
                if(!empty($member)){
                    if(json_decode($member['nickname']) != $nickname){        //更新头像或昵称
                        $data = array(
                            'avatar' => session('live_avatar_'.$live_topic['room_id']),
                            'reserve' => json_encode($nickname),    //nickname字段太短
                            'ip' => get_client_ip(),
                            'area' => $this->_getIpInfo(),
                            'phone_type' => $this->_phoneType()
                        );
                        M('live_member')->where($where_member)->save($data);
                    }
                    $auth = (($member['user_type'] == LiveModel::USER_ASSIST) &&
                        ($member['status'] == LiveModel::MEMBER_ACTIVE)) ? 1 : 0;
                }else{
                    $member = array(
                        'token' => $this->wxuser['token'],
                        'topic_id' => $topic_id,
                        'openid' => $openid,
                        'avatar' => session('live_avatar_'.$live_topic['room_id']),
                        'reserve' => json_encode($nickname),    //nickname字段太短
                        'ip' => get_client_ip(),
                        'area' => $this->_getIpInfo(),
                        'phone_type' => $this->_phoneType(),
                        'user_type' => LiveModel::USER_VIEWER
                    );
                    M('live_member')->add($member);
                    $auth = 0;
                }
                $this->ajaxReturn(array('status' => 1, 'auth' => $auth));
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    private function _statistics($topic_id, $type)
    {
        $where_topic["id"] = $topic_id;
        $live_topic = M('live_topic')->where($where_topic)->field('startdate,enddate')->find();
        $time = time();
        $start = strtotime($live_topic['startdate']);
        $end = strtotime($live_topic['enddate']);
        //if($time >= $start && $time <= $end) {       //正在直播时，用户在话题页面记录浏览量、点赞量和评论量
        $cache = S('live_topic_'.$topic_id);
        $page_view = isset($cache['page_view'])?$cache['page_view']:0;
        $praise_num = isset($cache['praise_num'])?$cache['praise_num']:0;
        $comment_num = isset($cache['comment_num'])?$cache['comment_num']:0;
        switch ($type){
            case 'page_view':
                $page_view += 1;
                break;
            case 'praise_num':
                $praise_num += 1;
                break;
            case 'comment_num':
                $comment_num += 1;
                break;
            default:
                break;
        }
        S('live_topic_'.$topic_id, array('page_view' => $page_view, 'praise_num' => $praise_num,
            'comment_num' => $comment_num), array('expire' => 800000));
        $play_time = ($time - $start)/3600;
        $decimal = explode('.', $play_time);
        $x = $decimal[0];       //整数部分
        $y = substr($decimal[1], 0, 1);       //小数部分
        if($y < 5){
            $playTime = ($x == 0) ? 0 : $x.'.0';
        }else{
            $playTime = ($x == 0) ? 0.5 : $x.'.5';
        }
        if($playTime != 0){
            $where_statistics["topic_id"] = $topic_id;
            $where_statistics["play_time"] = $playTime;
            $where_statistics["status"] = LiveModel::STAT_ACTIVE;
            $live_statistics = M('live_statistics')->where($where_statistics)->find();
            if(empty($live_statistics)){
                $stat = array('topic_id' => $topic_id, 'play_time' => $playTime, 'page_view' => $page_view,
                    'praise_num' => $praise_num, 'comment_num' => $comment_num);
                $add_id = M('live_statistics')->add($stat);
                if($add_id > 0){
                    S('live_topic_'.$topic_id, NULL);
                }
            }
        }
        //}
    }

    private function _getIpInfo()       //淘宝接口,根据ip查询所在区域信息
    {
        $ip = get_client_ip();
        $res = $this->curlGet("http://ip.taobao.com/service/getIpInfo.php?ip=$ip");
        $res = json_decode($res,true);
        $area = '';
        if($res['code'] == 0){
            $area = $res['data']['city'];
        }
        return $area;
    }

    private function _phoneType()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (stripos($user_agent, "iPhone") !== false) {
            $brand = 'iPhone';
        } else if (stripos($user_agent, "SAMSUNG") !== false || stripos($user_agent, "Galaxy") !== false
            || strpos($user_agent, "GT-") !== false || strpos($user_agent, "SCH-") !== false
            || strpos($user_agent, "SM-") !== false) {
            $brand = '三星';
        } else if (stripos($user_agent, "Huawei") !== false || stripos($user_agent, "Honor") !== false
            || stripos($user_agent, "H60-") !== false || stripos($user_agent, "H30-") !== false) {
            $brand = '华为';
        } else if (stripos($user_agent, "Lenovo") !== false) {
            $brand = '联想';
        } else if (strpos($user_agent, "MI-ONE") !== false || strpos($user_agent, "MI 1S") !== false
            || strpos($user_agent, "MI 2") !== false || strpos($user_agent, "MI 3") !== false
            || strpos($user_agent, "MI 4") !== false || strpos($user_agent, "MI-4") !== false) {
            $brand = '小米';
        } else if (strpos($user_agent, "HM NOTE") !== false || strpos($user_agent, "HM201") !== false) {
            $brand = '红米';
        } else if (stripos($user_agent, "Coolpad") !== false || strpos($user_agent, "8190Q") !== false
            || strpos($user_agent, "5910") !== false) {
            $brand = '酷派';
        } else if (stripos($user_agent, "ZTE") !== false || stripos($user_agent, "X9180") !== false
            || stripos($user_agent, "N9180") !== false || stripos($user_agent, "U9180") !== false) {
            $brand = '中兴';
        } else if (stripos($user_agent, "OPPO") !== false || strpos($user_agent, "X9007") !== false
            || strpos($user_agent, "X907") !== false || strpos($user_agent, "X909") !== false
            || strpos($user_agent, "R831S") !== false || strpos($user_agent, "R827T") !== false
            || strpos($user_agent, "R821T") !== false || strpos($user_agent, "R811") !== false
            || strpos($user_agent, "R2017") !== false) {
            $brand = 'OPPO';
        } else if (strpos($user_agent, "HTC") !== false || stripos($user_agent, "Desire") !== false) {
            $brand = 'HTC';
        } else if (stripos($user_agent, "vivo") !== false) {
            $brand = 'vivo';
        } else if (stripos($user_agent, "K-Touch") !== false) {
            $brand = '天语';
        } else if (stripos($user_agent, "Nubia") !== false || stripos($user_agent, "NX50") !== false
            || stripos($user_agent, "NX40") !== false) {
            $brand = '努比亚';
        } else if (strpos($user_agent, "M045") !== false || strpos($user_agent, "M032") !== false
            || strpos($user_agent, "M355") !== false) {
            $brand = '魅族';
        } else if (stripos($user_agent, "DOOV") !== false) {
            $brand = '朵唯';
        } else if (stripos($user_agent, "GFIVE") !== false) {
            $brand = '基伍';
        } else if (stripos($user_agent, "Gionee") !== false || strpos($user_agent, "GN") !== false) {
            $brand = '金立';
        } else if (stripos($user_agent, "HS-U") !== false || stripos($user_agent, "HS-E") !== false) {
            $brand = '海信';
        } else if (stripos($user_agent, "Nokia") !== false) {
            $brand = '诺基亚';
        } else {
            $brand = '其他手机';
        }
        return $brand;
    }

    //弹幕列表
    public function commentList()
    {
        $topic_id = I("get.topic_id", -1);
        $page = I("get.page", 1);
        $ask = I("get.ask", 0);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($page < 1){
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid page'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)) {
            $condition['topic_id'] = $topic_id;
            $condition['comment_type'] = LiveModel::USER_VIEWER;
            $condition['msg_type'] = ($ask == 0) ? array('in', LiveModel::MSG_TEXT.",".LiveModel::MSG_ASK) :
                LiveModel::MSG_ASK;
            if($this->_checkAssistAuth($topic_id)){
                $condition['status'] = array('in', array(LiveModel::COMMENT_APPLY, LiveModel::COMMENT_ACTIVE));
            }else{
                $condition['status'] = LiveModel::COMMENT_ACTIVE;
            }
            //记录用户查询时间，防止加载最新评论记录
            if($page == 1){
                session('commentListTime', date('Y-m-d H:i:s'));
            }else{
                if(session('commentListTime')){
                    $condition['createdate'] = array('ELT', session('commentListTime'));
                }
            }
            $page = ($page - 1) * 10;
            $live_comment = M("live_comment")->where($condition)->order("createdate desc")->limit($page, 10)->select();
            $list = array();
            if(!empty($live_comment)){
                foreach ($live_comment as $value){
                    $member[] = $value['openid'];
                }
                if(!empty($member)){
                    $member = array_flip(array_flip($member));
                    $where_member["topic_id"] = $topic_id;
                    $where_member["openid"] = array("in", $member);
                    $live_member = M("live_member")->where($where_member)->group("reserve,openid")
                        ->field('reserve,openid,user_type,status')->select();
                    if(!empty($live_member)){
                        $liveMember = $liveUser = $liveStatus = array();
                        foreach ($live_member as $value){
                            $liveMember[$value['openid']] = json_decode($value['reserve']);
                            $liveUser[$value['openid']] = $value['user_type'];
                            $liveStatus[$value['openid']] = $value['status'];
                        }
                        foreach ($live_comment as $value){
                            $reserve = $value['reserve'] ? json_decode($value['reserve'], true) : array();
                            $list[] = array(
                                'username' => $liveMember[$value['openid']],
                                'content' => json_decode($value['content']),
                                'chat_id' => $value['id'],
                                'date' => date('m月d日 H:i:s', strtotime($value['createdate'])),
                                'status' => ($liveUser[$value['openid']] == LiveModel::USER_ASSIST) ? 2 :
                                    $value['status'],
                                'silent' => ($liveUser[$value['openid']] == LiveModel::USER_ASSIST) ? 0 :
                                    ($liveStatus[$value['openid']] == LiveModel::MEMBER_SILENT ? 2 : 1),
                                'ask' => ($value['msg_type'] == LiveModel::MSG_TEXT) ? 0 : 1,
                                'reply' => ($reserve['replyStatus'] == 1) ? LiveModel::REPLY_TRUE :
                                    LiveModel::REPLY_FALSE
                            );
                        }
                        $this->ajaxReturn(array('status' => 1, 'list' => $list));
                    }else{
                        $this->ajaxReturn(array('status' => 1, 'list' => $list));
                    }
                }else{
                    $this->ajaxReturn(array('status' => 1, 'list' => $list));
                }
            }else{
                $this->ajaxReturn(array('status' => 1, 'list' => $list));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    //图文详情
    public function msgList()
    {
        $topic_id = I("get.topic_id", -1);
        $page = I("get.page", 1);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($page < 1){
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid page'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $condition['topic_id'] = $topic_id;
            $condition['comment_type'] = LiveModel::USER_ASSIST;
            if($this->_checkAssistAuth($topic_id)){
                $condition['status'] = array('in', array(LiveModel::COMMENT_APPLY, LiveModel::COMMENT_ACTIVE));
            }else{
                $condition['status'] = LiveModel::COMMENT_ACTIVE;
            }
            if($live_topic['sort'] == 2){
                $order = "createdate asc";
            }else{
                $order = "createdate desc";
            }
            //记录用户查询时间，防止加载最新评论记录
            if($page == 1){
                session('msgListTime', date('Y-m-d H:i:s'));
            }else{
                if(session('msgListTime')){
                    $condition['createdate'] = array('ELT', session('msgListTime'));
                }
            }
            $page = ($page - 1) * 10;
            $live_comment = M("live_comment")->where($condition)->order($order)->limit($page, 10)->select();
            $list = $msg = $reply = array();
            if(!empty($live_comment)){
                foreach ($live_comment as $value){
                    $member[] = $value['openid'];
                    if($value['msg_type'] == LiveModel::MSG_IMG || $value['msg_type'] == LiveModel::MSG_VOICE){
                        $msg[] = $value['id'];
                    }
                    if($value['comment_id'] != 0){
                        $reply[] = $value['comment_id'];
                    }
                }
                if(!empty($member)){
                    $member = array_flip(array_flip($member));
                    $where_member["topic_id"] = $topic_id;
                    $where_member["openid"] = array("in", $member);
                    $live_member = M("live_member")->where($where_member)->group("reserve,openid")
                        ->field('reserve,openid')->select();
                    $attach = $record_time = $reply_arr = array();
                    if(!empty($msg)){
                        $where_attach["comment_id"] = array("in", $msg);
                        $where_attach["status"] = LiveModel::ATTACH_ACTIVE;
                        $attachment = M("live_comment_attachment")->where($where_attach)
                            ->field("comment_id,content,reserve")->select();
                        if(!empty($attachment)){
                            foreach ($attachment as $value){
                                $attach[$value['comment_id']][] = C('SITE_URL').$value['content'];
                            }
                            foreach ($attachment as $value){
                                $record_time[$value['comment_id']] = $value['reserve'];
                            }
                        }
                    }
                    if(!empty($reply)){
                        $where_comment["topic_id"] = $topic_id;
                        $where_comment["id"] = array("in", $reply);
                        $live_reply = M("live_comment")->where($where_comment)->field('id,openid,content')
                            ->select();
                        if(!empty($live_reply)){
                            foreach ($live_reply as $value){
                                $where_mem["topic_id"] = $topic_id;
                                $where_mem["openid"] = $value['openid'];
                                $reply_member= M('live_member')->where($where_mem)->field('reserve')->find();
                                $reply_member_nickname = json_decode($reply_member['reserve'], true);
                                $reply_content = json_decode($value['content'], true);
                                $reply_arr[$value['id']] = '@'.$reply_member_nickname.' '.$reply_content;
                            }
                        }
                    }
                    if (!empty($live_member)) {
                        $liveMember = array();
                        foreach ($live_member as $value) {
                            $liveMember[$value['openid']] = json_decode($value['reserve']);
                        }
                        foreach ($live_comment as $value) {
                            $list[] = array(
                                'id' => $value['id'],
                                'nickname' => $liveMember[$value['openid']],
                                'chat_id' => $value['id'],
                                'msg' => $value['content']?json_decode($value['content']):'',
                                'time' => FactoryModel::friendlyDate(strtotime($value['createdate'])),
                                'msg_type' => $value['msg_type'],
                                'images' => ($value['msg_type'] == LiveModel::MSG_IMG) ?
                                    ($attach[$value['id']]?$attach[$value['id']]:array()) : array(),
                                'voice' => ($value['msg_type'] == LiveModel::MSG_VOICE) ?
                                    ($attach[$value['id']][0]?$attach[$value['id']][0]:'') : '',
                                'record_time' => ($value['msg_type'] == LiveModel::MSG_VOICE) ?
                                    $record_time[$value['id']]:0,
                                'reply' => ($value['comment_id'] > 0) ?
                                    ($reply_arr[$value['comment_id']]?$reply_arr[$value['comment_id']]:''): '',
                                'status' => $value['status'],
                                'link' => ($value['msg_type'] == LiveModel::MSG_IMG) ?
                                    (!empty($value["link"])?$value["link"]:"") : ""
                            );
                        }
                        $this->ajaxReturn(array('status' => 1, 'sort' => $live_topic["sort"], 'list' => $list));
                    } else {
                        $this->ajaxReturn(array('status' => 1, 'sort' => $live_topic["sort"], 'list' => $list));
                    }
                }else{
                    $this->ajaxReturn(array('status' => 1, 'sort' => $live_topic["sort"], 'list' => $list));
                }
            }else{
                $this->ajaxReturn(array('status' => 1, 'sort' => $live_topic["sort"], 'list' => $list));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function comment()
    {
        $topic_id = I("post.topic_id", -1);
        $content = I("post.content", "");
        $ask = I("post.ask", 0);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($content == ''){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'content missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $openid = session('live_openid_'.$live_topic['room_id']);
            if(!empty($openid)){
                $where_member["topic_id"] = $topic_id;
                $where_member["openid"] = $openid;
                $live_member = M('live_member')->where($where_member)->find();
                if($live_member['status'] != LiveModel::MEMBER_ACTIVE){
                    $this->ajaxReturn(array('status' => 2));        //被禁言
                }else{
                    //评论状态变成已评论
                    $where_mem["id"] = $live_member['id'];
                    M('live_member')->where($where_mem)->save(array('has_comment' => LiveModel::HAS_COMMENT_YES));
                    $data = array(
                        'openid' => $openid,
                        'topic_id' => $topic_id,
                        'content' => json_encode(htmlspecialchars($content)),
                        'comment_type' => LiveModel::USER_VIEWER,    //助理使用游客身份发弹幕
                        'msg_type' => ($ask == 0) ? LiveModel::MSG_TEXT : LiveModel::MSG_ASK,
                        'publishdate' => date("Y-m-d H:i:s")
                    );
                    $support = json_decode($live_topic['support'],true);
                    if($support['support_comment_check'] == LiveModel::SUPPORT_ACTIVE){
                        $data['status'] = LiveModel::COMMENT_APPLY;
                    }else{
                        $data['status'] = LiveModel::COMMENT_ACTIVE;
                    }

                    $added = M("live_comment")->add($data);
                    if($added > 0){
                        $this->_statistics($topic_id, 'comment_num');
                        $this->ajaxReturn(array('status' => 1, 'chat_id' => $added));
                    }else{
                        $this->ajaxReturn(array('status' => -5, 'errMsg' => 'server error'));
                    }
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function qrCode()
    {
        $live_id = I("get.live_id", -1);
        if($live_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'live_id missing'));
        }
        $where_room["id"] = $live_id;
        $where_room["status"] = LiveModel::ROOM_ACTIVE;
        $live_room = M("live_room")->where($where_room)->find();
        if(!empty($live_room)){
            $where_wxuser["id"] = $this->wxuser['id'];
            $headerpic = M('wxuser')->where($where_wxuser)->getField('headerpic');
            $qrImage = $headerpic?C('SITE_URL').$headerpic:C('SITE_URL').'/Public/images/home/zbgyEcode.jpg';
            $qrTxt = '长按二维码关注后,您可获得更多资讯';
            $forceQrTxt = '长按二维码,关注后方可继续收看';
            $this->ajaxReturn(array('status' => 1, 'qrImage' => $qrImage, 'qrTxt' => $qrTxt,
                'forceQrTxt' => $forceQrTxt));
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    private function _followStatus($live_id)
    {
        if($this->_is_weixin()){
            $openid = session('live_openid_'.$live_id);
            if(empty($openid)){
                return false;
            }
            $token = $this->_getAccessToken();
            if(empty($token)){
                return false;
            }
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $openid .
                "&lang=zh_CN";
            $res = $this->curlGet($url);
            $res = json_decode($res, 1);
            if(isset($res['subscribe'])){
                if($res['subscribe'] == 1){
                    return true;
                }else{
                    return false;
                }
            }else{
                if(isset($res['errcode']) && $res['errcode'] == 40001){
                    $url = "https://api.weixin.qq.com/cgi-bin/token?appid=" . $this->wxuser['appid'] . "&secret=" .
                        $this->wxuser['appsecret'] . "&grant_type=client_credential";
                    $res = $this->curlGet($url);
                    $res = json_decode($res, 1);
                    $token = isset($res['access_token']) ? $res['access_token'] : null;
                    S( 'access_token_'.$this->wxuser['token'], $token, 6300 );
                    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $openid .
                        "&lang=zh_CN";
                    $res = $this->curlGet($url);
                    $res = json_decode($res, 1);
                    if (isset($res['subscribe'])) {
                        if($res['subscribe'] == 1){
                            return true;
                        }else{
                            return false;
                        }
                    } else {
                        return false;
                    }
                }else if($res['errcode'] == 40003){
                    $code = I("get.code", "", "");
                    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->wxuser['appid'] .
                        "&secret=" . $this->wxuser['appsecret'] . "&code=" . $code . "&grant_type=authorization_code";
                    $exist = $this->curlGet($url);
                    $exist = json_decode($exist, 1);
                    $exist = isset($exist['openid']) ? $exist : null;
                    session('live_openid_'.$live_id, $exist);
                    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $exist .
                        "&lang=zh_CN";
                    $res = $this->curlGet($url);
                    $res = json_decode($res, 1);
                    if(isset($res['subscribe'])){
                        if($res['subscribe'] == 1){
                            return true;
                        }else{
                            return false;
                        }
                    }else{
                        if (isset($res['errcode']) && $res['errcode'] == 40001) {
                            $url = "https://api.weixin.qq.com/cgi-bin/token?appid=" . $this->wxuser['appid'] . "&secret=" .
                                $this->wxuser['appsecret'] . "&grant_type=client_credential";
                            $res = $this->curlGet($url);
                            $res = json_decode($res, 1);
                            $token = isset($res['access_token']) ? $res['access_token'] : null;
                            S( 'access_token_'.$this->wxuser['token'], $token, 6300 );
                            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" .
                                $exist . "&lang=zh_CN";
                            $res = $this->curlGet($url);
                            $res = json_decode($res, 1);
                            if (isset($res['subscribe'])) {
                                if($res['subscribe'] == 1){
                                    return true;
                                }else{
                                    return false;
                                }
                            } else {
                                return false;
                            }
                        }else{
                            return false;
                        }
                    }
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
    }

    private function _getAccessToken()
    {
        $access_token = S( 'access_token_'.$this->wxuser['token'] );
        if( !$access_token ){
            $url_get = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' .
                $this->wxuser['appid'] . '&secret=' . $this->wxuser['appsecret'];
            $json = json_decode($this->curlGet($url_get));
            if (!$json -> errmsg){
                $access_token = $json -> access_token;
                S( 'access_token_'.$this->wxuser['token'], $access_token, 6300 );
            }else{
                $this -> error('获取access_token发生错误：错误代码' . $json -> errcode .
                    ',微信返回错误信息：' . $json -> errmsg);
            }
        }
        return $access_token;
    }

    private function curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    public function roomShare()
    {
        $live_id = I("get.live_id", -1);
        if($live_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'live_id missing'));
        }
        $where_room["id"] = $live_id;
        $where_room["status"] = LiveModel::ROOM_ACTIVE;
        $live_room = M("live_room")->where($where_room)->field("share_title,share_desc,share_image,share_link")
            ->find();
        if(!empty($live_room)){
            $live_room['share_image'] = $live_room['share_image']?C('SITE_URL').$live_room['share_image']:'';
            $live_room['share_link'] = $live_room['share_link']?$live_room['share_link']:C('SITE_URL').
                '/Wap/Live/index?live_id='.$live_id;
            $this->ajaxReturn(array('status' => 1, 'share_data' => $live_room));
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid live_id'));
        }
    }

    public function topicShare()
    {
        $topic_id = I("get.topic_id", -1);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)
            ->field("share_title,share_desc,share_image,share_link")->find();
        if(!empty($live_topic)){
            $live_topic['share_image'] = $live_topic['share_image']?C('SITE_URL').$live_topic['share_image']:'';
            $live_topic['share_link'] = $live_topic['share_link']?$live_topic['share_link']:C('SITE_URL').
                '/Wap/Live/index?to=topic&live_id='.$live_topic['room_id'].'&topic_id='.$topic_id;
            $this->ajaxReturn(array('status' => 1, 'share_data' => $live_topic));
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    //----------------------------------websocket需要调用的接口开始-------------------------
    //查找一条评论，返回评论内容、是否开启评论
    public function getOneComment()
    {
        $chat_id = I("get.chat_id", -1);
        if($chat_id == -1 ){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'chat_id missing'));
        }
        $where_comment["id"] = $chat_id;
        $live_comment = M("live_comment")->where($where_comment)->find();
        if(!empty($live_comment)){
            $where_member["topic_id"] = $live_comment['topic_id'];
            $where_member["openid"] = $live_comment['openid'];
            $live_member = M('live_member')->where($where_member)->find();
            $nickname = $live_member['reserve'] ? json_decode($live_member['reserve'], true) : '';
            $msg = json_decode($live_comment['content'], true);
            $msg = $msg ? $msg : '';
            $date = date('m月d日 H:i:s', strtotime($live_comment['publishdate']));

            //助理发的都是友好时间格式
            if($live_comment["comment_type"] == LiveModel::USER_ASSIST){
                $date = FactoryModel::friendlyDate(strtotime($live_comment['publishdate']));
            }
            //是否开启评论审核
            $support_comment_check = 0;
            $where_topic["id"] = $live_comment['topic_id'];
            $live_topic = M("live_topic")->where($where_topic)->field("support")->find();
            if(!empty($live_topic)){
                $support = json_decode($live_topic['support'], true);
                if($support['support_comment_check'] == LiveModel::SUPPORT_ACTIVE){
                    $support_comment_check = 1;
                }
            }else{
                $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid chat_id'));
            }
            //提问图标
            $ask = 0;
            if($live_comment['msg_type'] == LiveModel::MSG_ASK){
                $ask = 1;
            }
            //图片、音频附件
            $attach = array();
            $record_time = 0;
            $link = "";
            if($live_comment['msg_type'] == LiveModel::MSG_IMG){
                $where_attach["comment_id"] = $chat_id;
                $live_comment_attachment = M('live_comment_attachment')->where($where_attach)->select();
                if(!empty($live_comment_attachment)){
                    foreach ($live_comment_attachment as $value){
                        $attach[] = C('SITE_URL').$value['content'];
                    }
                }
                $date = FactoryModel::friendlyDate(strtotime($live_comment['publishdate']));
                $link = !empty($live_comment["link"]) ? $live_comment["link"] : "";
            }
            if($live_comment['msg_type'] == LiveModel::MSG_VOICE){
                $attach = '';
                $where_attach["comment_id"] = $chat_id;
                $live_comment_attachment = M('live_comment_attachment')->where($where_attach)->find();
                if(!empty($live_comment_attachment)){
                    $attach = C('SITE_URL').$live_comment_attachment['content'];
                    $record_time = $live_comment_attachment['reserve'];
                }
                $date = FactoryModel::friendlyDate(strtotime($live_comment['publishdate']));
            }
            //上墙内容
            $reply = '';
            if($live_comment['comment_id'] > 0){
                $where_com["id"] = $live_comment['comment_id'];
                $reply_comment = M('live_comment')->where($where_com)->find();
                $where_mem["topic_id"] = $live_comment['topic_id'];
                $where_mem["openid"] = $reply_comment['openid'];
                $reply_member = M('live_member')->where($where_mem)->find();
                $reply_msg = json_decode($reply_comment['content'], true);
                $reply_nickname = $reply_member['reserve'] ? json_decode($reply_member['reserve'], true) : '';
                $reply = '@'.$reply_nickname.' '.$reply_msg;
            }
            $this->ajaxReturn(array('status' => 1, 'nickname' => $nickname, 'date' => $date, 'msg' => $msg,
                'attach' => $attach, 'record_time' => $record_time, 'reply' => $reply, 'ask' => $ask,
                'support_comment_check' => $support_comment_check, 'link' => $link));
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid chat_id'));
        }
    }

    //统计在线人数，返回虚假人数
    public function online()
    {
        $topic_id = I("get.topic_id", -1);
        if($topic_id == -1 ){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->field("support")->find();
        if(!empty($live_topic)){
            $support = json_decode($live_topic['support'], true);
            if($support['support_online_num'] == LiveModel::SUPPORT_ACTIVE){
                $where_member["topic_id"] = $topic_id;
                $where_member["status"] = LiveModel::MEMBER_ACTIVE;
                $popularity_num = M("live_member")->where($where_member)->count();
                $popularity_num = $popularity_num + $support['online_multi'];
                $this->ajaxReturn(array('status' => 1, 'popularity_num' => $popularity_num));
            }else{
                $this->ajaxReturn(array('status' => 1, 'popularity_num' => 0));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    //点赞
    public function praise()
    {
        $topic_id = I("get.topic_id", -1);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $this->_statistics($topic_id, 'praise_num');
            $this->ajaxReturn(array('status' => 1));
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    //禁言切换
    public function getSupportCommentAll()
    {
        $topic_id = I('get.topic_id', -1);
        if ($topic_id == -1) {
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M('live_topic')->where($where_topic)->find();
        $support = json_decode($live_topic['support'], true);
        $support_comment_all = ($support['support_comment']==LiveModel::SUPPORT_ACTIVE)?1:0;
        $this->ajaxReturn(array('status' => 1, 'support_comment_all' => $support_comment_all));
    }
    //----------------------------------websocket需要调用的接口结束-------------------------

    //2. 助理方
    private function _checkAssistAuth($topic_id)
    {
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M('live_topic')->where($where_topic)->find();
        $openid = session('live_openid_'.$live_topic['room_id']);
        if(empty($openid)){
            return false;
        }
        $where['topic_id'] = $topic_id;
        $where['openid'] = $openid;
        $where['status'] = LiveModel::MEMBER_ACTIVE;
        $where['user_type'] = array('NEQ', LiveModel::USER_VIEWER);
        $live_member = M('live_member')->where($where)->find();
        if(!empty($live_member)){
            return true;
        }else{
            return false;
        }
    }

    public function assistLogin()
    {
        $topic_id = I('post.topic_id', -1);
        $password = I('post.password', '');
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($password == ''){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'password missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M('live_topic')->where($where_topic)->find();
        if(!empty($live_topic)){
            if($password == $live_topic['assist_pwd']){
                $openid = session('live_openid_'.$live_topic['room_id']);
                $avatar = session('live_avatar_'.$live_topic['room_id']);
                $nickname = session('live_nickname_'.$live_topic['room_id']);
                $where_member["topic_id"] = $topic_id;
                $where_member["openid"] = $openid;
                $live_member = M('live_member')->where($where_member)->find();
                if(!empty($live_member)){
                    $where_mem["id"] = $live_member['id'];
                    M('live_member')->where($where_mem)->save(array('user_type' => LiveModel::USER_ASSIST));
                }else{
                    $member = array(
                        'token' => $this->wxuser['token'],
                        'topic_id' => $topic_id,
                        'openid' => $openid,
                        'avatar' => $avatar,
                        'reserve' => $nickname?json_encode($nickname):'',        //nickname字段太短，用json保存表情
                        'ip' => get_client_ip(),
                        'area' => $this->_getIpInfo(),
                        'phone_type' => $this->_phoneType(),
                        'user_type' => LiveModel::USER_ASSIST
                    );
                    M('live_member')->add($member);
                }
                $this->ajaxReturn(array('status' => 1));
            }else{
                $this->ajaxReturn(array('status' => -6, 'errMsg' => 'login fail'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function assistReply()
    {
        $topic_id = I("post.topic_id", -1);
        $reply_id = I("post.reply_id", 0);
        $content = I("post.content", "");
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($reply_id == 0){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'reply_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $openid = session('live_openid_'.$live_topic['room_id']);
            if(!empty($openid)){
                if($this->_checkAssistAuth($topic_id)){
                    $reserve = json_encode(array('replyStatus' => 1));
                    $where_comment["id"] = $reply_id;
                    $has_reply = M('live_comment')->where($where_comment)->save(array('reserve' => $reserve));
                    $data = array(
                        'openid' => $openid,
                        'topic_id' => $topic_id,
                        'content' => json_encode(htmlspecialchars($content)),
                        'msg_type' => LiveModel::MSG_TEXT,
                        'status' => LiveModel::COMMENT_ACTIVE,
                        'comment_type' => LiveModel::USER_ASSIST,
                        'comment_id' => $reply_id,
                        'publishdate' => date("Y-m-d H:i:s")
                    );
                    $added = M("live_comment")->add($data);
                    if($added > 0){
                        $this->_statistics($topic_id, 'comment_num');
                        $this->ajaxReturn(array('status' => 1, 'chat_id' => $added));
                    }else{
                        $this->ajaxReturn(array('status' => -5, 'errMsg' => 'server error'));
                    }
                }else{
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => 'please login first'));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function assistVoice()
    {
        $topic_id = I('post.topic_id', -1);
        $content = I('post.content', '');
        $record_time = I('post.record_time', 0);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($content == ''){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'content missing'));
        }
        if($record_time == 0){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'record_time missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $openid = session('live_openid_'.$live_topic['room_id']);
            if(!empty($openid)){
                if($this->_checkAssistAuth($topic_id)){
                    $media = $this->_downloadWxFile($content);
                    if($media != ''){
                        $comment = array(
                            'openid' => $openid,
                            'topic_id' => $topic_id,
                            'comment_type' => LiveModel::USER_ASSIST,
                            'msg_type' => LiveModel::MSG_VOICE,
                            'publishdate' => date("Y-m-d H:i:s")
                        );
                        $add_id = M('live_comment')->add($comment);
                        $attach = array(
                            'comment_id' => $add_id,
                            'content' => $media,
                            'reserve' => $record_time
                        );
                        M('live_comment_attachment')->add($attach);
                        $this->ajaxReturn(array('status' => 1, 'chat_id' => $add_id, 'result' => C('SITE_URL').$media));
                    }else{
                        $this->ajaxReturn(array('status' => -5, 'errMsg' => 'ffmpeg error'));
                    }
                }else{
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => 'please login first'));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    //下载并保存微信服务器amr音频文件
    private function _downloadWxFile($media_id){
        $token = $this->_getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=' . $token . '&media_id=' . $media_id;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);

        $prefix = explode("/", $httpinfo["content_type"]);
        $time = time();
        $filename_amr = $time . "." . $prefix[1];
        $filename_mp3 = $time . ".mp3";
        $www_dir_unsyn = 'Public/unsyn_uploads/live/' . date('Ymd');
        $www_dir_syn = 'Public/Uploads/live/' . date('Ymd');
        $dir_unsyn = '/var/www/zjdaily/trunk/Public/unsyn_uploads/live/' . date('Ymd');  //不同步文件路径，存放amr和mp3
        $dir_syn = '/var/www/zjdaily/trunk/Public/Uploads/live/' . date('Ymd');    //同步文件路径，存放mp3
        $path_amr = $dir_unsyn.'/'.$filename_amr;
        $path_mp3 = $dir_unsyn.'/'.$filename_mp3;
        $path_mp3_syn = $dir_syn.'/'.$filename_mp3;
        $media_url = '/'.$www_dir_syn.'/'.$filename_mp3;
        //1、创建目录
        if (!is_dir($www_dir_unsyn)) mkdir($www_dir_unsyn);
        if (!is_dir($www_dir_syn)) mkdir($www_dir_syn);
        //2、下载amr文件到非同步文件
        $local_file = fopen($www_dir_unsyn. '/' . $filename_amr, 'w');
        fwrite($local_file, $package);
        fclose($local_file);
        //3、ffmpeg转码mp3
        $log1 = $log2 = "";
        $status1 = $status2 = 1;
        exec('ffmpeg -i ' . $path_amr . ' ' . $path_mp3, $log1, $status1);
        if($status1 != 0){
            return "";
        }
        //4、同步文件到新目录
        exec('cp ' . $path_mp3 . ' ' . $path_mp3_syn, $log2, $status2);
        if($status2 != 0){
            return "";
        }
        return $media_url;
    }

    //直接发送图文
    public function assistMsgPhoto()
    {
        $topic_id = I('post.topic_id', -1);
        $content = I('post.content', '');
        $img = I('post.img', '');
        $link = I('post.link', '');
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($content == '' && $img == ''){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'content or img missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $openid = session('live_openid_'.$live_topic['room_id']);
            if(!empty($openid)){
                if($this->_checkAssistAuth($topic_id)){
                    $comment = array(
                        'openid' => $openid,
                        'topic_id' => $topic_id,
                        'content' => json_encode(htmlspecialchars($content)),
                        'comment_type' => LiveModel::USER_ASSIST,
                        'msg_type' => LiveModel::MSG_IMG,
                        'publishdate' => date("Y-m-d H:i:s"),
                        'link' => $link
                    );
                    $add_id = M('live_comment')->add($comment);
                    $imgs = explode('|', $img);
                    $return_img = array();
                    foreach ($imgs as $value){
                        $images = explode('@', $value);
                        $photo = $images[0];
                        $orientation = $images[1];
                        if($photo != ''){
                            if(substr($photo, 0, 4) == "http"){
                                $attach = array(
                                    'comment_id' => $add_id,
                                    'content' => str_replace(C("SITE_URL"), "", $photo)
                                );
                            }else{
                                $ret = FactoryModel::ajaxImgUpload($photo, 'live');
                                if($ret['code'] == -1){
                                    $where_comment["id"] = $add_id;
                                    M('live_comment')->where($where_comment)->save(array("status" =>
                                        LiveModel::COMMENT_DELETE));
                                    $this->ajaxReturn(array('status' => -8, 'errMsg' => 'img upload fail'));
                                }
                                $root = substr($ret['msg'],1);
                                $image = new Image();
                                $image->open($root);
                                $width = $image->width();
                                $height = $image->height();
                                $explode = explode(".",$root);
                                $rename = $explode[0].'thumb.'. $explode[1];
                                $image->thumb($width,$height)->save($rename);

                                if($orientation == 6){
                                    $this->imgTurn($rename,1);
                                }
                                $return_img[] =  C('SITE_URL'). '/' . $rename;
                                $attach = array(
                                    'comment_id' => $add_id,
                                    'content' => '/'.$rename
                                );
                            }
                            M('live_comment_attachment')->add($attach);
                        }
                    }
                    $this->ajaxReturn(array('status' => 1, 'chat_id' => $add_id, 'result' => $return_img));
                }else{
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => 'please login first'));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    private function imgTurn($src, $direction=1)
    {
        $ext = pathinfo($src)['extension'];
        switch ($ext) {
            case 'gif':
                $img = imagecreatefromgif($src);
                break;
            case 'jpg':
            case 'jpeg':
                $img = imagecreatefromjpeg($src);
                break;
            case 'png':
                $img = imagecreatefrompng($src);
                break;
            default:
                die('图片格式错误!');
                break;
        }
        $width = imagesx($img);
        $height = imagesy($img);
        $img2 = imagecreatetruecolor($height, $width);
        //顺时针旋转90度
        if ($direction == 1) {
            for ($x = 0; $x < $width; $x++) {
                for ($y = 0; $y < $height; $y++) {
                    imagecopy($img2, $img, $height - 1 - $y, $x, $x, $y, 1, 1);
                }
            }
        } else if ($direction == 2) {
            //逆时针旋转90度
            for ($x = 0; $x < $height; $x++) {
                for ($y = 0; $y < $width; $y++) {
                    imagecopy($img2, $img, $x, $y, $width - 1 - $y, $x, 1, 1);
                }
            }
        }
        switch ($ext) {
            case 'gif':
                imagegif($img2, $src, 60);
                break;
            case 'jpg':
            case 'jpeg':
                imagejpeg($img2, $src, 60);
                break;
            case 'png':
                imagepng($img2, $src, 60);
                break;
            default:
                die('图片格式错误!');
                break;
        }
        imagedestroy($img);
        imagedestroy($img2);
    }

    public function assistShare()
    {
        $topic_id = I("get.topic_id", -1);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)
            ->field("share_title,share_desc,share_image,share_link")->find();
        if(!empty($live_topic)){
            $live_topic['share_title'] = '直播助理邀请';
            $live_topic['share_image'] = $live_topic['share_image']?C('SITE_URL').$live_topic['share_image']:'';
            $live_topic['share_link'] = C('SITE_URL').'/Wap/Live/index?to=assistant&live_id='.
                $live_topic['room_id'].'&topic_id='.$topic_id;
            $this->ajaxReturn(array('status' => 1, 'share_data' => $live_topic));
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    //草稿箱列表
    public function draftList()
    {
        $topic_id = I("get.topic_id", -1);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)) {
            $openid = session('live_openid_' . $live_topic['room_id']);
            if (!empty($openid)) {
                if ($this->_checkAssistAuth($topic_id)) {
                    $where_comment["topic_id"] = $topic_id;
                    $where_comment["comment_type"] = LiveModel::USER_ASSIST;
                    $where_comment["msg_type"] = LiveModel::MSG_IMG;
                    $where_comment["status"] = LiveModel::COMMENT_DRAFT;
                    $list = M("live_comment")->where($where_comment)->field("id as chat_id,content,createdate")
                        ->order("createdate desc")->select();
                    if(!empty($list)){
                        $attach = array();
                        foreach($list as $value){
                            $chat_ids[] = $value["chat_id"];
                        }
                        if(!empty($chat_ids)){
                            $where_attach["comment_id"] = array("in", $chat_ids);
                            $where_attach["status"] = LiveModel::ATTACH_ACTIVE;
                            $attachments = M("live_comment_attachment")->where($where_attach)
                                ->field("comment_id,content")->order("createdate asc")->select();
                            if(!empty($attachments)){
                                foreach ($attachments as $value_attach){
                                    $attach[$value_attach["comment_id"]] = !empty($value_attach["content"]) ?
                                        C("SITE_URL").$value_attach["content"] : "";
                                }
                            }
                        }
                        foreach($list as &$value_list){
                            $value_list["content"] = json_decode($value_list["content"], true);
                            $value_list["date"] = date("m月d日 H:i", strtotime($value_list["createdate"]));
                            $value_list["thumb"] = !empty($attach[$value_list["chat_id"]]) ?
                                $attach[$value_list["chat_id"]] : "";
                            unset($value_list["createdate"]);
                        }
                    }
                    $this->ajaxReturn(array('status' => 1, 'list' => $list));
                }else{
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => 'please login first'));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    //草稿箱详情
    public function draftDetail()
    {
        $topic_id = I("get.topic_id", -1);
        $chat_id = I("get.chat_id", 0);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($chat_id == 0){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'chat_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)) {
            $openid = session('live_openid_' . $live_topic['room_id']);
            if (!empty($openid)) {
                if ($this->_checkAssistAuth($topic_id)) {
                    $where_comment["id"] = $chat_id;
                    $where_comment["topic_id"] = $topic_id;
                    $where_comment["comment_type"] = LiveModel::USER_ASSIST;
                    $where_comment["msg_type"] = LiveModel::MSG_IMG;
                    $where_comment["status"] = LiveModel::COMMENT_DRAFT;
                    $comment = M("live_comment")->where($where_comment)->field("id,content,link")->find();
                    $img = array();
                    if(!empty($comment)){
                        $where_attach["comment_id"] = $comment["id"];
                        $where_attach["status"] = LiveModel::ATTACH_ACTIVE;
                        $attachment = M("live_comment_attachment")->where($where_attach)->field("content")
                            ->order("createdate asc")->select();
                        if(!empty($attachment)){
                            foreach ($attachment as $value){
                                if(!empty($value["content"])){
                                    $img[] = C("SITE_URL").$value["content"];
                                }
                            }
                        }
                    }
                    $link = !empty($comment["link"]) ? $comment["link"] : "";
                    $this->ajaxReturn(array('status' => 1, 'content' => json_decode($comment["content"], true),
                        'img' => $img, 'link' => $link));
                }else{
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => 'please login first'));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    //增加或编辑草稿箱
    public function draftComment()
    {
        $chat_id = I('post.chat_id', 0);
        $topic_id = I('post.topic_id', -1);
        $content = I('post.content', '');
        $img = I('post.img', '');
        $link = I('post.link', '');
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($content == '' && $img == ''){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'content or img missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $openid = session('live_openid_'.$live_topic['room_id']);
            if(!empty($openid)){
                if($this->_checkAssistAuth($topic_id)){
                    $comment = array(
                        'openid' => $openid,
                        'topic_id' => $topic_id,
                        'content' => json_encode(htmlspecialchars($content)),
                        'comment_type' => LiveModel::USER_ASSIST,
                        'msg_type' => LiveModel::MSG_IMG,
                        'status' => LiveModel::COMMENT_DRAFT,
                        'link' => $link
                    );
                    if($chat_id == 0){
                        $chat_id = M('live_comment')->add($comment);
                    }else{
                        $where_comment["id"] = $chat_id;
                        M("live_comment")->where($where_comment)->save(array("content" =>
                            json_encode(htmlspecialchars($content)), 'link' => $link));
                    }
                    //图片更新
                    $imgs = explode('|', $img);
                    $where_attach["comment_id"] = $chat_id;
                    $where_attach["status"] = LiveModel::ATTACH_ACTIVE;
                    $attachment = M("live_comment_attachment")->where($where_attach)->field("id,content")->select();
                    if(!empty($attachment)){
                        foreach ($attachment as $value_attach){
                            if(!empty($value_attach["content"])){
                                $attach_img[$value_attach["id"]] = C("SITE_URL").$value_attach["content"];
                            }
                        }
                        if(!empty($attach_img)){
                            foreach ($attach_img as $key => $value_a_i){
                                foreach ($imgs as $value_img){
                                    if($value_img == $value_a_i){
                                        $attach_no_del[] = $key;
                                    }
                                }
                            }
                            if(!empty($attach_no_del)){
                                $where_del["id"] = array("not in", $attach_no_del);
                            }
                            $where_del["comment_id"] = $chat_id;
                            M("live_comment_attachment")->where($where_del)->save(array("status" =>
                                LiveModel::ATTACH_DELETE));
                        }
                    }

                    $return_img = array();
                    foreach ($imgs as $value){
                        $images = explode('@', $value);
                        $photo = $images[0];
                        $orientation = $images[1];
                        if($photo != '' && substr($photo, 0, 4) != "http"){
                            $ret = FactoryModel::ajaxImgUpload($photo, 'live');
                            if($ret['code'] == -1){
                                $where_comment["id"] = $chat_id;
                                M('live_comment')->where($where_comment)->save(array("status" =>
                                    LiveModel::COMMENT_DELETE));
                                $this->ajaxReturn(array('status' => -8, 'errMsg' => 'img upload fail'));
                            }
                            $root = substr($ret['msg'],1);
                            $image = new Image();
                            $image->open($root);
                            $width = $image->width();
                            $height = $image->height();
                            $explode = explode(".",$root);
                            $rename = $explode[0].'thumb.'. $explode[1];
                            $image->thumb($width,$height)->save($rename);

                            if($orientation == 6){
                                $this->imgTurn($rename,1);
                            }
                            $return_img[] =  C('SITE_URL'). '/' . $rename;
                            $attach = array(
                                'comment_id' => $chat_id,
                                'content' => '/'.$rename
                            );
                            M('live_comment_attachment')->add($attach);
                        }
                    }
                    $this->ajaxReturn(array('status' => 1, 'chat_id' => $chat_id));
                }else{
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => 'please login first'));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function deleteComment()
    {
        $topic_id = I("post.topic_id", -1);
        $chat_id = I("post.chat_id", 0);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($chat_id == 0){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'chat_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $openid = session('live_openid_'.$live_topic['room_id']);
            if(!empty($openid)){
                if($this->_checkAssistAuth($topic_id)){
                    $where_comment["id"] = $chat_id;
                    $where_comment["topic_id"] = $topic_id;
                    $live_comment = M('live_comment')->where($where_comment)->find();
                    if($live_comment['comment_id'] != 0){
                        $reserve = json_encode(array('replyStatus' => LiveModel::REPLY_FALSE));
                        $where_com["id"] = $live_comment['comment_id'];
                        $where_com["topic_id"] = $topic_id;
                        M("live_comment")->where($where_com)->save(array("reserve" => $reserve));
                    }
                    M("live_comment")->where($where_comment)->save(array("status" => LiveModel::COMMENT_DELETE));
                    $this->ajaxReturn(array('status' => 1));
                }else{
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => 'please login first'));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function passComment()
    {
        $topic_id = I("post.topic_id", -1);
        $chat_id = I("post.chat_id", 0);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($chat_id == 0){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'chat_id missing'));
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M("live_topic")->where($where_topic)->find();
        if(!empty($live_topic)){
            $openid = session('live_openid_'.$live_topic['room_id']);
            if(!empty($openid)){
                if($this->_checkAssistAuth($topic_id)){
                    //检查用户是否被禁言
                    $where_comment["id"] = $chat_id;
                    $where_comment["topic_id"] = $topic_id;
                    $live_comment = M('live_comment')->where($where_comment)->find();
                    if(!empty($live_comment)){
                        $where_member["topic_id"] = $topic_id;
                        $where_member["openid"] = $live_comment['openid'];
                        $live_member = M('live_member')->where($where_member)->find();
                        if($live_member['status'] == LiveModel::MEMBER_SILENT){
                            $this->ajaxReturn(array('status' => 2));
                        }else{
                            $where_com["id"] = $live_comment['id'];
                            $data = array(
                                "status" => LiveModel::COMMENT_ACTIVE,
                                "publishdate" => date("Y-m-d H:i:s")
                            );
                            M("live_comment")->where($where_com)->save($data);
                            $this->ajaxReturn(array('status' => 1));
                        }
                    }else{
                        $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid chat_id'));
                    }
                }else{
                    $this->ajaxReturn(array('status' => -7, 'errMsg' => 'please login first'));
                }
            }else{
                $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function silentMember()
    {
        $topic_id = I('post.topic_id', -1);
        $chat_id = I("post.chat_id", 0);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($chat_id == 0){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'chat_id missing'));
        }
        $where_comment["id"] = $chat_id;
        $where_comment["topic_id"] = $topic_id;
        $live_comment = M('live_comment')->where($where_comment)->find();
        $where_member["topic_id"] = $topic_id;
        $where_member["openid"] = $live_comment['openid'];
        M('live_member')->where($where_member)->save(array('status' => LiveModel::MEMBER_SILENT));
        $this->ajaxReturn(array('status' => 1));
    }

    public function activateMember()
    {
        $topic_id = I('post.topic_id', -1);
        $chat_id = I("post.chat_id", 0);
        if($topic_id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'topic_id missing'));
        }
        if($chat_id == 0){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'chat_id missing'));
        }
        $where_comment["id"] = $chat_id;
        $where_comment["topic_id"] = $topic_id;
        $live_comment = M('live_comment')->where($where_comment)->find();
        $where_member["topic_id"] = $topic_id;
        $where_member["openid"] = $live_comment['openid'];
        M('live_member')->where($where_member)->save(array('status' => LiveModel::MEMBER_ACTIVE));
        $this->ajaxReturn(array('status' => 1));
    }

    //3. app端
    public function appTopics()
    {
        $uid = I("get.uid", -1);
        if($uid == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'uid missing'));
        }
        $where_user["id"] = $uid;
        $where_user["status"] = LiveModel::USER_ACTIVE;
        $live_user = M('live_user')->where($where_user)->find();
        $where_room["id"] = $live_user['roomid'];
        $where_room["status"] = LiveModel::ROOM_ACTIVE;
        $live_room = M('live_room')->where($where_room)->find();
        if(!empty($live_room)){
            $condition['room_id'] = $live_user['roomid'];
            $condition['topic_type'] = array('NEQ', LiveModel::TOPIC_TYPE_MSG);
            $condition['status'] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
            $live_topic = M("live_topic")->where($condition)->order("createdate desc")->select();
            $list = array();
            $time = time();
            if(!empty($live_topic)){
                foreach ($live_topic as $value){
                    $startdate = strtotime($value['startdate']);
                    $enddate = strtotime($value['enddate']);
                    if($enddate < $time){       //0 已结束 1正在直播 2即将开始
                        $status = 0;
                        $order = 3;
                    }elseif($startdate > $time){
                        $status = 2;
                        $order = 2;
                    }else{
                        $status = 1;
                        $order = 1;
                    }
                    $flag[]=$order;
                    $list[] = array(
                        'topic_id' => $value['id'],
                        'title' => $value['topic_title'],
                        'image' => $value['video_poster']?C('SITE_URL').$value['video_poster']:'',
                        'status' => $status,
                        'date' => date('Y-m-d', strtotime($value['startdate'])),
                        'order' => $order
                    );
                }
                array_multisort($flag, SORT_ASC, $list);
                $this->ajaxReturn(array('status' => 1, 'list' => $list));
            }else{
                $this->ajaxReturn(array('status' => 1, 'list' => $list));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid uid'));
        }
    }

    public function appLogin()
    {
        $account = I('post.account', '');
        $password = I('post.password', '');
        if($account == ''){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'account missing'));
        }
        if($password == ''){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'password missing'));
        }
        $where_user["account"] = $account;
        $where_user["status"] = LiveModel::USER_ACTIVE;
        $live_user = M('live_user')->where($where_user)->find();
        if(!empty($live_user)){
            $password = md5($password);
            if($password == $live_user['password']){
                $avatar = $live_user['avatar']?C('SITE_URL').$live_user['avatar']:'';
                $uid = $live_user['id'];
                $this->ajaxReturn(array('status' => 1, 'msg' => 'login success', 'avatar' => $avatar, 'uid' => $uid));
            }else{
                $this->ajaxReturn(array('status' => -1, 'errMsg' => 'login fail'));
            }
        }else{
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'login fail'));
        }
    }

    public function appStartStream()
    {
        $uid = I('post.uid', -1);
        $topic_id = I('post.topic_id', -1);
        if($uid == -1){
            $this->ajaxReturn( array('status' => -1, 'errMsg' => 'uid missing') );
        }
        if($topic_id == -1){
            $this->ajaxReturn( array('status' => -1, 'errMsg' => 'topic_id missing') );
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M('live_topic')->where($where_topic)->find();
        //已正常
        $where["id"] = $topic_id;
        M('live_topic')->where($where)->save(array('status' => LiveModel::TOPIC_ACTIVE));
        if(!empty($live_topic)){
            $where_user["id"] = $uid;
            $where_user["status"] = LiveModel::USER_ACTIVE;
            $live_user = M('live_user')->where($where_user)->find();
            $data = array(
                'userid' => $uid,
                'roomid' => $live_user['roomid'],
                'startdate' => date('Y-m-d H:i:s'),
                'reserve' => $topic_id
            );
            M('live_stat')->add($data);
            $this->ajaxReturn(array('status' => 1));
        }else{
            $this->ajaxReturn(array('status' =>-2, 'errMsg' => 'invalid topic_id'));
        }
    }

    public function appPauseStream()
    {
        $uid = I('post.uid', -1);
        $topic_id = I('post.topic_id', -1);
        if($uid == -1){
            $this->ajaxReturn( array('status' => -1, 'errMsg' => 'uid missing') );
        }
        if($topic_id == -1){
            $this->ajaxReturn( array('status' => -1, 'errMsg' => 'topic_id missing') );
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M('live_topic')->where($where_topic)->find();
        $where_stat["userid"] = $uid;
        $where_stat["reserve"] = $topic_id;
        $live_stat = M('live_stat')->where($where_stat)->order('startdate desc')->find();
        //已暂停
        $where["id"] = $topic_id;
        M('live_topic')->where($where)->save(array('status' => LiveModel::TOPIC_PAUSE));
        if($live_stat['enddate'] == null){
            $where_end["id"] = $live_stat['id'];
            M('live_stat')->where($where_end)->save(array('enddate' => date('Y-m-d H:i:s')));
            //数据统计
            $cache = S('live_topic_'.$topic_id);
            $start = strtotime($live_topic['startdate']);
            $end = strtotime($live_topic['enddate']);
            $play_time = ($end - $start)/3600;
            $decimal = explode('.', $play_time);
            $x = $decimal[0];       //整数部分
            $y = substr($decimal[1], 0, 1);       //小数部分
            if($y < 5){
                $playTime = ($x == 0) ? 0 : $x.'.0';
            }else{
                $playTime = ($x == 0) ? 0.5 : $x.'.5';
            }
            if($playTime != 0){
                $where_statistics["topic_id"] = $topic_id;
                $where_statistics["play_time"] = $playTime;
                $where_statistics["status"] = LiveModel::STAT_ACTIVE;
                $live_statistics = M('live_statistics')->where($where_statistics)->find();
                if(empty($live_statistics)){
                    $stat = array('topic_id' => $topic_id, 'play_time' => $playTime, 'page_view' => $cache['page_view'],
                        'praise_num' => $cache['praise_num'], 'comment_num' => $cache['comment_num']);
                    $add_id = M('live_statistics')->add($stat);
                    if($add_id > 0){
                        S('live_topic_'.$topic_id, NULL);
                    }
                }
            }
        }
        $this->ajaxReturn(array('status' => 1));
    }

    public function appEndStream()
    {
        $socket = I('get.socket', 0);
        if($socket == 1){
            $uid = I('get.uid', -1);
            $topic_id = I('get.topic_id', -1);
        }else{
            $uid = I('post.uid', -1);
            $topic_id = I('post.topic_id', -1);
        }
        if($uid == -1){
            $this->ajaxReturn( array('status' => -1, 'errMsg' => 'uid missing') );
        }
        if($topic_id == -1){
            $this->ajaxReturn( array('status' => -1, 'errMsg' => 'topic_id missing') );
        }
        $where_topic["id"] = $topic_id;
        $where_topic["status"] = array('in', LiveModel::TOPIC_ACTIVE.','.LiveModel::TOPIC_PAUSE);
        $live_topic = M('live_topic')->where($where_topic)->find();
        $where_stat["userid"] = $uid;
        $where_stat["reserve"] = $topic_id;
        $live_stat = M('live_stat')->where($where_stat)->order('startdate desc')->find();
        //已正常
        $where["id"] = $topic_id;
        M('live_topic')->where($where)->save(array('status' => LiveModel::TOPIC_ACTIVE));
        if($live_stat['enddate'] == null){
            $where_end["id"] = $live_stat['id'];
            M('live_stat')->where($where_end)->save(array('enddate' => date('Y-m-d H:i:s')));
            //数据统计
            $cache = S('live_topic_'.$topic_id);
            $start = strtotime($live_topic['startdate']);
            $end = strtotime($live_topic['enddate']);
            $play_time = ($end - $start)/3600;
            $decimal = explode('.', $play_time);
            $x = $decimal[0];       //整数部分
            $y = substr($decimal[1], 0, 1);       //小数部分
            if($y < 5){
                $playTime = ($x == 0) ? 0 : $x.'.0';
            }else{
                $playTime = ($x == 0) ? 0.5 : $x.'.5';
            }
            if($playTime != 0){
                $where_statistics["topic_id"] = $topic_id;
                $where_statistics["play_time"] = $playTime;
                $where_statistics["status"] = LiveModel::STAT_ACTIVE;
                $live_statistics = M('live_statistics')->where($where_statistics)->find();
                if(empty($live_statistics)){
                    $stat = array('topic_id' => $topic_id, 'play_time' => $playTime, 'page_view' => $cache['page_view'],
                        'praise_num' => $cache['praise_num'], 'comment_num' => $cache['comment_num']);
                    $add_id = M('live_statistics')->add($stat);
                    if($add_id > 0){
                        S('live_topic_'.$topic_id, NULL);
                    }
                }
            }
        }
        $this->ajaxReturn(array('status' => 1));
    }

    public function xcx_liveList()
    {
        $email = I("post.email", "");
        $live_list = array();
        if (empty($email)) {
            $this->ajaxReturn($live_list);
        }

        $cond['email'] = $email;
        $wx_id = M("users")->where($cond)->getField("wx_id");
        if (empty($wx_id)) {
            $this->ajaxReturn($live_list);
        }

        $cond_wx['id'] = $wx_id;
        $token = M("wxuser")->where($cond_wx)->getField("token");
        if (empty($token)) {
            $this->ajaxReturn($live_list);
        }

        $cond_room['reserve'] = $token;
        $cond_room['status'] = LiveModel::STAT_ACTIVE;
        $live_list = M("live_room")->where($cond_room)->select();
        $this->ajaxReturn($live_list);
    }
    //=============================================wap接口结束=========================================================
}